package com.lagou.edu.minicat.core;

import com.lagou.edu.minicat.Request;
import com.lagou.edu.minicat.Response;
import com.lagou.edu.minicat.base.LifecycleBase;
import lombok.Data;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

@Data
public class Connector extends LifecycleBase {

    private int port;
    private Service service;

    private ServerSocket serverSocket;

    @Override
    protected void initInternal() {
        try {
            serverSocket = new ServerSocket(port);
            System.out.println(this.getClass().getName() + " init port " + port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void startInternal() {
        try {
            while (true) {
                // 开始接收请求
                Socket socket = this.serverSocket.accept();

                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();

                Request request = new Request(inputStream);
                Response response = new Response(outputStream);

                //查找Context
                Engine engine = getService().getEngine();
                Host host = engine.getHost();
                if (!request.getHost().equals(host.getName())) {
                    continue;
                }

                Context[] contexts = host.getContexts();
                for (Context context : contexts) {
                    String[] urlArr = request.getUrl().split("/");
                    if (context.getContextName().equals(urlArr[1])) {
                        request.setContext(context);
                        response.setHost(host);
                    }
                }

                // 查找servlet并且执行。
                if (request.getContext() != null) {
                    String contextName = request.getContext().getContextName();
                    String urlPattern = request.getUrl().replaceFirst("/" + contextName, "");
                    Wrapper wrapper = request.getContext().findWrapper(urlPattern);
                    if (wrapper == null) {
                        try {
                            response.outputHtml1(request.getUrl());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        wrapper.getServlet().service(request, response);
                    }
                }
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
